import { reqCartList, reqDeleteCartById, reqUpdateCheckedById } from "@/api";

const state = {
  cartList: [],
};

const mutations = {
  GET_CART_LIST(state, cartList) {
    state.cartList = cartList;
  },
};

const actions = {
  // 获取购物车列表数据
  async getCartList({ commit }) {
    const result = await reqCartList();
    if (result.code == 200) {
      commit("GET_CART_LIST", result.data);
    }
  },
  // 删除购物车某一产品
  async deleteCartListBySkuId({ commit },skuId) {
    let result = await reqDeleteCartById(skuId);
    if(result.code == 200){
      return "ok";
    }else{
      return Promise.reject(new Error("faile"));
    }
  },
  // 删除全部勾选的产品
  deleteAllCheckedCart({ dispatch, getters }){
    // context:小仓库， commit[提交mutations修改state] getters[计算属性] dispatch[派发action] state[当前仓库数据]

    // 获取购物车中全部产品 
    let PromiseAll = [];
    getters.cartList.forEach(item => {
      item.cartInfoList.forEach(shop => {
        let promise = shop.isChecked == 1? dispatch('deleteCartListBySkuId', shop.skuId): '';
        console.log(promise)
        PromiseAll.push(promise)
      })
    });
    //只要全部的p1|p2....都成功，返回结果即为成功
    //如果有一个失败，返回即为失败结果
    return Promise.all(PromiseAll);
  },
  // 修改购物车某一产品的选中状态
  async updateCheckedById( { commit }, { skuId, isChecked }) {
    let result = await reqUpdateCheckedById(skuId,isChecked);
    if(result.code == 200){
      return "ok";
    }else{
      return Promise.reject(new Error("faile"));
    }
  },
  // 修改全部产品的状态
  updateAllCartIsChecked({ dispatch, getters }, isChecked) {
    let PromiseAll = []
    getters.cartList.forEach(item => {
      item.cartInfoList.forEach(shop => {
        let promise = dispatch("updateCheckedById", {
          skuId: shop.skuId,
          isChecked,
        });
        PromiseAll.push(promise)
      })
    });
    return Promise.all(PromiseAll);
  }
};
const getters = {
  cartList(state) {
    return state.cartList || {};
  },
};
export default {
  state,
  mutations,
  actions,
  getters,
};
